package com.liangdemo.web.thread;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Name LiangErLe
 * @date 2022/6/9 16:01
 */
public class ThreadDemo4_1 {
    public static void main(String[] args) throws IOException {
        MyTask t1 = new ThreadDemo4_1.MyTask("线程1", 3, true);
        MyTask t2 = new ThreadDemo4_1.MyTask("线程2", 4, true);
        MyTask t3 = new ThreadDemo4_1.MyTask("线程3", 1, false);
        List<MyTask> tasks = new ArrayList<>();
        tasks.add(t1);
        tasks.add(t2);
        tasks.add(t3);


        tasks.stream().forEach(t -> {
            t.start();
        });
        for (; ; ) {
            for (MyTask task : tasks) {
                if (task.getResult() == Result.FATLED) {
                    System.exit(0);
                }
            }
        }
    }


    /**
     * 线程执行结果的集中状态
     * NOTEND；正在运行
     * SUCCESSED：成功
     * FATLED：失败
     */
    private static enum Result {
        NOTEND, SUCCESSED, FATLED
    }


    private static class MyTask extends Thread {

        private Result result = Result.NOTEND;
        private String name;
        private int timeInSeconds;
        private boolean success;

        public MyTask(String name, int timeInSeconds, boolean success) {
            this.name = name;
            this.timeInSeconds = timeInSeconds;
            this.success = success;
        }

        public Result getResult() {
            return result;
        }

        public void run() {
            try {
                Thread.sleep(timeInSeconds * 1000);
                System.out.println(name + "  任务结束");
                result = success ? Result.SUCCESSED : Result.FATLED;
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

        }
    }


}